import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAppSelector } from "../app/hooks";

interface IProps {
  component: React.ComponentType;
  [key: string]: any; // 任意属性
  // [key: number]: any; // 表示数组
}

// 权限保护
const PrivateRoute = ({ component: Component, ...rest }: IProps) => {
  let location = useLocation(); // 类似 window.location 对象
  const token = useAppSelector((state) => state.user.token);

  return token ? (
    <Component {...rest} />
  ) : (
    // 重定向登录页，并且记录想要访问的页面
    <Navigate to="/login" state={{ from: location }} />
  );
};

export default PrivateRoute;
